//
//  WmcTeamCloudAlbumHomeVM.swift
//  YPWatermarkCamera
//
//  Created by 赵洋 on 2022/9/8.
//

import RxRelay
import SVProgressHUD
import UIKit

class WmcTeamCloudAlbumHomeVM: WmcBaseVM {
    /// 列表数据
    let listData: BehaviorRelay<[WmcMediaTeamResourceModel]> = .init(value: [])
    /// 请求错误
    let error: BehaviorRelay<Error?> = .init(value: nil)
    /// 最近有数据的日期
    var recentHasDataDate: WmcMediaTakePhotoDayModel?
    /// 所有有数据的日期
    var hasDataDates: [WmcMediaTakePhotoDayModel] = .init()
    /// 是否显示选择日期弹窗
    var showCalendar: Bool = false
    /// 选择的日期
    var selectedDate: WmcMediaTakePhotoDayModel?

    var teamAblum: WmcMediaTeamAlbumModel?

    /// 接口返回的原始数据
    private(set) var originalDataSource: [WmcMediaTeamResourceModel.WmcMediaResourceModel] = []
    /// 预览页面数据
    private(set) var browserDataSource: [WmcMedia] = []

    override func config() {}

    /// 根据日期筛选
    /// - Parameters:
    ///   - completion: 回调
    ///   - failure: 失败
    func fetchPhotoCalendarList(succeed: ((_ recentDate: WmcMediaTakePhotoDayModel?, _ dates: [WmcMediaTakePhotoDayModel]) -> Void)?) {
        SVProgressHUD.show()
        let endDate = (WmcDateManager.shared.networkDate.value ?? Date()).yp.string("yyyy-MM-dd")
        guard let busId = teamAblum?.busId else { return }
        WmcMediaTeamAlbumAPI.fetchTakePhotoCalendar(busId: busId, startDate: "2020-01-01", endDate: endDate).subscribe(onNext: { [weak self] list in
            guard let weakSelf = self else { return }
            var result: [WmcMediaTakePhotoDayModel] = []
            for item in list {
                result.append(item)
            }
            if let first = result.first {
                if weakSelf.selectedDate != nil {
                    weakSelf.recentHasDataDate = weakSelf.selectedDate
                } else {
                    weakSelf.recentHasDataDate = first
                    weakSelf.selectedDate = first
                }
            } else {
                weakSelf.selectedDate = nil
            }
            weakSelf.hasDataDates.removeAll()
            weakSelf.hasDataDates.append(contentsOf: result)

            guard let succeed = succeed else {
                return
            }
            succeed(weakSelf.selectedDate, weakSelf.hasDataDates)
            SVProgressHUD.dismiss()
        }, onError: {[weak self] error in
            SVProgressHUD.dismiss()
            WmcHudManager.toast(error)
            guard let weakSelf = self else { return }
            weakSelf.error.accept(error)
        }).disposed(by: rx.disposeBag)
    }

    /// 团队资源列表
    /// DocumentUrl: http://yapi.3pvr.com/project/219/interface/api/3126
    /// - Parameters:
    ///   - teamId: 团队id
    ///   - date: 日期 (yyyy-MM-dd 格式)
    /// - Returns: Observable<[WmcMediaTeamResourceModel]>
    func fetchTeamResource(date: String? = nil) {
        guard let teamId = teamAblum?.teamId else { return }
        WmcHudManager.loading()
        WmcMediaTeamManagerAPI.fetchTeamResource(teamId: teamId, date: date).subscribe { [weak self] list in
            guard let weakSelf = self else { return }
            weakSelf.listData.accept(list)
            /// 处理预览数据
            weakSelf.processBrowseDatasource(list: list)
            WmcHudManager.dismiss()
        } onError: { [weak self] error in
            guard let weakSelf = self else { return }
            WmcHudManager.dismiss()
            WmcHudManager.toast(error)
            weakSelf.error.accept(error)
        }.disposed(by: rx.disposeBag)
    }
    
    /// 团队资源列表
    /// - Parameters:
    ///   - date: 日期
    ///   - success: 成功
    ///   - failure: 失败
    /// - Returns: description
    func fetchTeamResource(date: String? = nil,success: ((_ list: [WmcMediaTeamResourceModel]) -> Void)?,failure: ((_ error: Error) -> Void)?) -> Void {
        guard let teamId = teamAblum?.teamId else { return }
        WmcHudManager.loading()
        WmcMediaTeamManagerAPI.fetchTeamResource(teamId: teamId, date: date).subscribe { [weak self] list in
            guard let weakSelf = self else { return }
            weakSelf.listData.accept(list)
            /// 处理预览数据
            weakSelf.processBrowseDatasource(list: list)
            WmcHudManager.dismiss()
            guard let success = success else {
                return
            }
            success(list)
        } onError: { [weak self] error in
            guard let weakSelf = self else { return }
            WmcHudManager.dismiss()
            WmcHudManager.toast(error)
            weakSelf.error.accept(error)
            guard let failure = failure else {
                return
            }
            failure(error)
        }.disposed(by: rx.disposeBag)
    }
    
    /// 处理预览数据
    /// - Parameter list: list description
    /// - Returns: description
    func processBrowseDatasource(list: [WmcMediaTeamResourceModel]) {
        browserDataSource.removeAll()
        originalDataSource.removeAll()
        list.forEach { item in
            item.resources.forEach { photo in
                var mediaItem = WmcMedia()
                if photo.resourceType == 0 {
                    mediaItem = WmcImage(url: photo.url)
                    mediaItem.memberId = item.getMember().memberId ?? 0
                }
                if photo.resourceType == 1 {
                    mediaItem = WmcVideo(url: photo.url)
                    mediaItem.memberId = item.getMember().memberId ?? 0
                }
                self.browserDataSource.append(mediaItem)
                self.originalDataSource.append(photo)
            }
        }
    }
}

extension WmcTeamCloudAlbumHomeVM {
    func deleteImage(index: Int, success: @escaping () -> Void, failure: @escaping (Error?) -> Void) {
        if index < originalDataSource.count {
            let model = originalDataSource[index]
            guard let busId = teamAblum?.busId else { return }
            WmcMediaTeamAlbumAPI.deletePhoto(id: model.id, busId: Int(busId) ?? 0).subscribe(onNext: { [weak self] _ in
                guard let weakSelf = self else { return }
                weakSelf.originalDataSource.remove(at: index)
                weakSelf.browserDataSource.remove(at: index)
                WmcNotificationManager.shared.post(type: .deletePhotoSucceed, object: nil)
                success()
            }, onError: { error in
                failure(error)
            }).disposed(by: rx.disposeBag)
        } else {
            failure(nil)
        }
    }

    func fetchVideoShare(index: Int, success: @escaping (WmcMediaShareModel) -> Void, failure: @escaping (Error?) -> Void) {
        if index < originalDataSource.count {
            let model = originalDataSource[index]
            guard let busId = teamAblum?.busId else { return }
            WmcMediaTeamAlbumAPI.fetchVideoShareInfo(busId: Int(busId) ?? 0, id: model.id).subscribe(onNext: { r in
                success(r)
            }, onError: { error in
                failure(error)
            }).disposed(by: rx.disposeBag)
        } else {
            failure(nil)
        }
    }
}

extension WmcTeamCloudAlbumHomeVM {
    /// 获取自己作为成员的模型
    /// - Returns: description
    func getSelfMember(succeed: ((WmcTeamMemberModel) -> Void)?) {
        guard let teamId = teamAblum?.teamId else {
            return
        }
        WmcHudManager.loading()
        WmcMediaTeamManagerAPI.fetchMemberList(id: teamId).subscribe { list in
            WmcHudManager.dismiss()
            list.forEach { member in
                if member.isSelf() {
                    guard let succeed = succeed else {
                        return
                    }
                    succeed(member)
                }
            }
        } onError: { error in
            WmcHudManager.dismiss()
            WmcHudManager.toast(error)
        }.disposed(by: rx.disposeBag)
    }
}

extension WmcTeamCloudAlbumHomeVM {
    /// 创建示例数据
    /// - Returns: description
    func createExampleData() -> WmcMediaTeamResourceModel {
        let exampleData = WmcMediaTeamResourceModel()
        exampleData.area = "成都市武侯区.天府软件园"
        exampleData.remark = "张三"
        exampleData.name = "张三"

        let resoure = WmcMediaTeamResourceModel.WmcMediaResourceModel()
        resoure.hm = "00:00"
        resoure.url = "https://static101.cdqlkj.cn/r/fb49/101/pb/v/20220810/15573036393520660600000.mp4"
        resoure.resourceType = 1
        resoure.lat = 30.537271
        resoure.lon = 104.056002

        let models = [resoure]
        exampleData.resources = models

        return exampleData
    }
}

extension WmcTeamCloudAlbumHomeVM {
    /// 获取自己作为成员的模型
    /// - Returns: description
    func getCurrentMember(model: WmcMediaTeamResourceModel, succeed: ((WmcTeamMemberModel) -> Void)?) {
        guard let teamId = teamAblum?.teamId else {
            return
        }
        WmcHudManager.loading()
        WmcMediaTeamManagerAPI.fetchMemberList(id: teamId).subscribe { list in
            WmcHudManager.dismiss()
            list.forEach { member in
                if model.getMember().memberId == member.memberId {
                    guard let succeed = succeed else {
                        return
                    }
                    succeed(member)
                }
            }
        } onError: { error in
            WmcHudManager.dismiss()
            WmcHudManager.toast(error)
        }.disposed(by: rx.disposeBag)
    }
}
